package com.byxy.controller;

import com.byxy.po.User;


import com.byxy.service.UserService;

import com.byxy.util.MD5Util;
import com.byxy.util.RandomNum;

import com.byxy.util.SMSUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.io.IOException;
import java.util.Date;

@Controller
public class UserController {


    @Resource
    private UserService userService;

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @GetMapping("/register")
    public String reg() {
        return "register";
    }

    @PostMapping("/doreg")
    public String reg(@RequestParam String username,
                      @RequestParam String password) {

        User u = new User();
            while (true) {
                Integer account = Integer.parseInt(RandomNum.vcode(8));
                u.setAccount(account);
                if (userService.selectOne(u)==null) {
                    u.setAccount(account);
                    u.setFixed_salt(RandomNum.getRandomString(8));
                    u.setUser_name(username);
                    u.setPassword(MD5Util.inputPassToDbPass(password, u.getFixed_salt()));
                    u.setUser_time(new Date());
                    userService.insertSelective(u);
                    return "redirect:/login";
                }
            }
    }

    @PostMapping("/dologin")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session) {
        if (username.length()<=8){
            User account = new User();
            account.setAccount(Integer.parseInt(username));
            User accountLogin = (User) userService.selectOne(account);
            if (accountLogin != null){
                String mPassword = MD5Util.inputPassToDbPass(password, accountLogin.getFixed_salt());
                if (mPassword.equals(accountLogin.getPassword())) {
                    session.setAttribute("account", accountLogin.getAccount());
                    session.setAttribute("userName", accountLogin.getUser_name());
                    return "redirect:/index";
                }
                return "redirect:/login";
            }return "redirect:/login";
        }else {
            User phone = new User();
            phone.setPhone(username);
            User  email= new User();
            email.setPhone(username);
            /* accountLogin.setEmail(username);*/
            User phoneLogin = (User) userService.selectOne(phone);
            User emailLogin = (User) userService.selectOne(email);
            if (phoneLogin != null) {
                String mPassword = MD5Util.inputPassToDbPass(password, phoneLogin.getFixed_salt());
                if (mPassword.equals(phoneLogin.getPassword())) {
                    session.setAttribute("account", phoneLogin.getAccount());
                    session.setAttribute("userName", phoneLogin.getUser_name());
                    return "redirect:/index";
                }
            } else if (emailLogin != null) {
                String mPassword = MD5Util.inputPassToDbPass(password, emailLogin.getFixed_salt());
                if (mPassword.equals(emailLogin.getPassword())) {
                    session.setAttribute("account", emailLogin.getAccount());
                    session.setAttribute("userName", emailLogin.getUser_name());
                    return "redirect:/index";
                }
            }
            return "redirect:/login";
        }
        }


    /*    @PostMapping(value="/sendsms")
        public void sendsms(@PathVariable String mobile, HttpServletResponse response){
            try {
                response.getWriter().write(userService.sendSms(mobile));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    @PostMapping("/updateUser")
    public String updateUser(@RequestParam String username,
                             @RequestParam String password,
                             HttpSession session) {

        User u = new User();
        u.setUser_name(username);
        User user = (User) userService.selectOne(u);
        BeanUtils.copyProperties(user, u);
        u.setFixed_salt(RandomNum.getRandomString(8));
        String mpassword = MD5Util.inputPassToDbPass(password, u.getFixed_salt());
        u.setPassword(mpassword);
        u.setUpdate_time(new Date());
        userService.updateByPrimaryKey(u);
        session.removeAttribute("userName");
        session.removeAttribute("account");
        return "redirect:/login";
    }

    @GetMapping("/exit")
    public String exit(HttpSession session) {
        session.removeAttribute("userName");
        session.removeAttribute("account");
        return "redirect:/index";
    }
    @GetMapping("/myaccount")
    public String myaccount(HttpSession session) {
        return "myaccount";
    }

    @PostMapping ("/phoneVerify")
    @ResponseBody
    public boolean phoneVerify(@RequestParam String memPhone, HttpSession session){
        try{
            //随机4位数验证码，我这里使用的hutool随机数工具类进行生成
            String code = RandomNum.vcode( 6 );
            JSONObject json  =null;
            //发送测试
            SMSUtils.sendShortMessage( SMSUtils.VALIDATE_CODE, memPhone, code );
            session.setAttribute(memPhone,code);
            session.setMaxInactiveInterval(300);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }
    @PostMapping ("/getPhone")
    public String getPhone(@RequestParam String username,@RequestParam String memPhone,@RequestParam String msgCode,@RequestParam String password, HttpSession session){

        String code=session.getAttribute(memPhone).toString();

            if (code.equals(msgCode)){
                User u = new User();
                while (true){
                    Integer account=Integer.parseInt(RandomNum.vcode(8));
                    u.setAccount(account);
                    if (userService.selectOne(u)==null){
                        u.setAccount(account);
                        u.setFixed_salt(RandomNum.getRandomString(8));
                        u.setUser_name(username);
                        u.setPhone(memPhone);
                        u.setPassword(MD5Util.inputPassToDbPass(password, u.getFixed_salt()));
                        u.setUser_time(new Date());
                        userService.insertSelective(u);
                        return "redirect:/login";
                    }
                }

            }
            return "redirect:/register";

    }
    @PostMapping ("/phoneLogin")
    public String phoneLogin(@RequestParam String memPhone ,@RequestParam String msgCode, HttpSession session){

        String code=session.getAttribute(memPhone).toString();
        User u = new User();
        u.setPhone(memPhone);
        User user=(User) userService.selectOne(u);
        if (!user.equals(null)&&code.equals(msgCode)){
            session.setAttribute("account", user.getAccount());
            session.setAttribute("userName", user.getUser_name());
            session.removeAttribute(memPhone);
            return "redirect:/index";

        }

        return "redirect:/login";

    }
}

